<template lang="html">
  <div class="panel-order">
    <div class="head">
      <h4>我的订单</h4>
      <div class="search">
        <input type="text" v-model="searchKey" class="input" placeholder="商品名称/订单编号" />
        <button class="btn" @click="handleSearchOrder()">搜索</button>
      </div>
    </div>
    <div class="body">
      <ul class="status-title">
        <li :class="{'active': orderStatus == index}" v-for="(item, index) in orderStatusText" @click="handleChangeStatus(index)">
          <div class="title">{{ item.title }}</div>
          <span class="num" v-if="item.nums>0">{{ item.nums }}</span>
          <span class="line"></span>
        </li>
      </ul>
      <div class="table-head table-info" v-if="orderList.length">
        <div class="order-info">订单详情</div>
        <div class="order-price">金额</div>
        <div class="order-consignee">收货人</div>
        <div class="order-status">订单状态</div>
        <div class="order-operation">操作</div>
      </div>
      <div class="table-body table-info" v-loading="loading" v-if="orderList.length">
        <div class="checkAllPlay" v-if="orderStatus == 1">
          <el-checkbox v-model="checkedAll" @change="handleChangeAll()">全选</el-checkbox>
          <a href="javascript:;" @click="handleMergePlay()" :class="{'active':checkedLen>0}">{{ checkedLen >1 ? '合并支付' : '立即支付' }}</a>
        </div>
        <div class="item" v-for="(item, index) in orderList">
          <div class="hd">
            <div class="time"><el-checkbox v-model="item.checked" @change="handleChangeItem(item)" v-if="orderStatus == 1"></el-checkbox>下单时间：{{ item.createTime }}</div>
            <div class="number">订单编号：<span>{{ item.orderNo }}</span></div>
            <div class="storeName"><span @click="routeToPath('/factory/'+item.factoryId)">{{ item.factoryName }}</span><img src="@/assets/images/cart/cart_01.png" @click="handleChat()" /></div>
          </div>
          <div class="bd">
            <div class="order-info">
              <ul class="order-product-list">
                <li v-for="(panel, i) in item.orderItemDTOList" v-if="item.orderType == 1">
                  <img :src="URL.PIC + panel.productPic" @click="routeToPath('/product/'+panel.productId)" />
                  <div class="info">
                    <div class="left">
                      <div class="title" @click="routeToPath('/product/'+panel.productId)" >{{ panel.productName }}</div>
                      <div class="specifications">{{ panel.specifications }}</div>
                      <div class="price">¥ {{ panel.productPrice }}</div>
                    </div>
                    <div class="right">
                      x{{ panel.quantity }}
                    </div>
                  </div>
                </li>
                <li v-if="item.orderType == 2">
                  <!-- <router-link class="xorder-list-icon" :to="{ name: 'SearchXorderDetail', params: {id:item.protocolItemDTOList[0].protocolId} }">
                    <img src="@/assets/images/xorder/xorder-list-icon2.png">
                  </router-link> -->
                  <a class="xorder-list-icon" @click="routeToPath('/search/xorderDetail/'+item.protocolItemDTOList[0].protocolId, 'mall')">
                    <img src="@/assets/images/xorder/xorder-list-icon2.png">
                  </a>
                  <div class="info">
                    <div class="left">
                      <!-- <router-link class="title" :to="{ name: 'SearchXorderDetail', params: {id:item.protocolItemDTOList[0].protocolId} }">
                        {{ item.protocolItemDTOList[0].templateName }}
                      </router-link> -->
                      <a class="title" @click="routeToPath('/search/xorderDetail/'+item.protocolItemDTOList[0].protocolId, 'mall')">
                        {{ item.protocolItemDTOList[0].templateName }}
                      </a>
                      <div v-if="item.orderType == 2" class="orderType">
                        协议订单
                      </div>
                      <div class="price">备货时间：{{ item.protocolItemDTOList[0].stockupTime }}天 <span v-if="item.isNotPay == 1" class="font-red">（有未付款项）</span> </div>
                    </div>
                  </div>
                </li>
              </ul>
            </div>
            <div class="order-price">
              <div class="price" v-if="item.orderType == 1">
                支付金额
                <span>¥ {{ item.payAmount }}</span>
              </div>
              <div class="price" v-if="item.orderType == 2">
                订单总金额
                <span>¥ {{ item.amount }}</span>
              </div>
            </div>
            <div class="order-consignee">
              <!-- <div class="consignee" v-if="item.orderType == 2">协议订单</div> -->
              <div class="consignee">{{ item.consignee }}</div>
            </div>
            <div class="order-status">
              <!-- 未付款订单超时自动取消 或 未付款订单买家主动取消的订单 -->
              <!-- 已申请取消订单并退款，卖家已同意时 -->
              <div class="status" v-if="item.orderType == 1 && item.orderStatus == 6 && item.cancelStatus == 1 || item.orderType == 1 && item.cancelStatus == 4">已关闭</div>
              <!-- 已付款但未发货的订单 -->
              <div class="status" v-if="item.orderType == 1 && item.orderStatus == 2">待发货</div>

              <div class="status" v-if="item.orderType == 2 && item.orderStatus == 2">
                <span v-if="item.stockStatus == 2">
                  备货中
                </span>
                <span v-if="item.stockStatus == 3">
                  备货完成
                </span>
              </div>

              <!-- 未付款订单 -->
              <div class="status" v-if="item.orderStatus == 1">待付款</div>
              <!-- 未付款订单 -->
              <div class="status" v-if="item.orderStatus == 5">已完成</div>

              <div class="status" v-if="item.orderType == 2 && item.orderStatus == 8">待审核</div>
              <div class="status" v-if="item.orderType == 2 && item.orderStatus == 7">待处理</div>

              <div class="status" v-if="item.orderType == 2 && item.orderStatus == 6 && item.cancelStatus == 6">
                <span>
                  已关闭
                </span>
              </div>
              <div class="status" v-if="item.orderType == 2 && item.orderStatus == 6 && item.cancelStatus != 6">
                <span>
                  已取消
                </span>
              </div>
            </div>
            <div class="order-operation">
              <router-link v-if="item.orderType == 2 && item.orderStatus == 7" class="btn-pay" :to="{name:'XorderDetail', query:{ orderNo: item.orderNo }}">上传协议</router-link>
              <a href="javascript:;" class="btn-pay" v-if="item.orderStatus == 1" @click="handlePay(item.orderNo, item)">立即支付</a>
              <a href="javascript:;" class="btn-pay mt-10" v-if="item.orderStatus == 2" @click="handleRemind(item.orderNo)">提醒发货</a>
              <a href="javascript:;" class="btn-pay" v-if="item.orderStatus == 3" @click="handleConfirmReceipt(item.orderNo)">确认收货</a>
              <!-- <router-link :to="{name:'CommentsList', query:{ orderNo: item.orderNo, factoryName: item.factoryName }}" class="btn-evaluation" v-if="item.orderStatus == 4">评价</router-link> -->
              <a @click="routeToPath('/member/orders/commentsList?orderNo=' + item.orderNo+'&factoryName='+item.factoryName)" class="btn-evaluation" v-if="item.orderStatus == 4">评价</a>

              <a href="javascript:;" v-if="item.orderStatus == 2" @click="handleCancelSalesOrder(item.id)">申请售后</a>
              <a href="javascript:;" v-if="item.orderType == 1 && item.orderStatus == 1" @click="handleCancelOrder(item.id)">取消订单</a>
              <a href="javascript:;" v-if="item.orderType == 2 && item.orderStatus == 7 || item.orderType == 2 && item.orderStatus == 1 || item.orderType == 2 && item.orderStatus == 8"
               @click="handleCancelOrder(item.id)">取消订单</a>
              <span v-if="item.orderType == 1">
                <a href="javascript:;" v-if="item.orderStatus == 4 || item.orderStatus == 5 || item.orderStatus == 6" @click="handleAgainBuy(item.orderNo)">再次购买</a>
              </span>

              <!-- <router-link :to="{name:item.orderType == 2?'XorderDetail':'MemberOrderDetail', query:{ orderNo: item.orderNo }}">查看详情</router-link> -->

              <nuxt-link v-if="item.orderType == 1" :to="'/member/orders/'+item.orderNo">查看详情</nuxt-link>
              <nuxt-link v-if="item.orderType == 2" :to="'/member/xorders/'+item.orderNo">查看详情</nuxt-link>

              <!-- <a href="#">申请售后</a> -->
            </div>
          </div>
        </div>
      </div>
      <div class="order-nodata" v-else>
        <img src="@/assets/images/member/notorder.png" />
        <p>暂时还没有订单哦~</p>
      </div>
    </div>
    <pagination v-show="total>0" :total="total" :page.sync="page" :limit.sync="size" @pagination="getOrderList" />
  </div>
</template>

<script>

import Pagination from '@/components/Pagination'
import { getOrderList, getOrderNums, reminderShipment, cancelOrder, againBuyOrder, applyCancelOrder, confirmReceipt } from '@/api/order'
export default {
  name: 'MemberOrder',
  components: {
    Pagination
  },
  data() {
    return{
      loading: true,
      orderStatusText: [
        {
          'title':'全部订单',
          'nums': 0
        },
        {
          'title':'待付款',
          'nums': 0
        },
        {
          'title':'待发货',
          'nums': 0
        },
        {
          'title':'待收货',
          'nums': 0
        },
        {
          'title':'待评价',
          'nums': 0
        },
      // {
      //  'title':'退换/售后',
      //  'nums': 0
      // }
      ],
      orderList: [],
      orderNums: {},
      orderStatus: (this.getUrlParams('orderStatus') != undefined && this.getUrlParams('orderStatus') != '') ? this.getUrlParams('orderStatus') : 0,
      page: 1,
      size: 10,
      total: 0,
      searchKey: '',//订单搜索关键词
      checkedAll: false, //合并支付全选
      checkedLen: 0
    }
  },
  created() {
    this.getOrderList();
  },
  methods: {
    handleChat() {
      this.$message({
        message: '供应商暂未开启客服功能',
        type: 'warning'
      });
    },
    //切换状态
    handleChangeStatus(index) {
      this.orderStatus = index;
      this.page = 1;
      this.$router.push({
        path: '/member/orders',
        query: {
          orderStatus: index
        }
      })
      this.getOrderList();
    },
    //搜索
    handleSearchOrder() {
      if(this.searchKey == ''){
        this.$message({
          type: 'error',
          message: '请输入商品名称或订单编号'
        });
        return;
      }
      this.getOrderList();
    },
    //获取订单列表
    getOrderList() {
      this.loading = true
      if(this.orderStatus == 1){
        this.size = 100
      }else{
        this.size = 10
      }
      const params = {
        "orderStatus": this.orderStatus,
        "orderType": this.orderType,
        "size": this.size,
        "page": this.page,
        "searchKey": this.searchKey
      }
      getOrderList(params).then(res => {
        if(res.code == 200){
          this.orderList = res.data.list
          this.total = res.data.total
          this.getOrderNums()
          setTimeout(() => {
            this.loading = false
          }, 300)
        }
      })
    },
    //获取订单状态对应数量
    getOrderNums() {
      getOrderNums().then(res => {
        if(res.code == 200){
          this.orderNums = res.data;
          this.orderStatusText[1].nums = res.data.pendingPaymentNum
          this.orderStatusText[2].nums = res.data.pendingShippedNum
          this.orderStatusText[3].nums = res.data.pendingReceivedNum
          this.orderStatusText[4].nums = res.data.pendingEvaluatedNum
        }
      })
    },
    //提醒发货
    handleRemind(orderNo) {
      const params = {
        orderNo: orderNo
      }
      reminderShipment(params).then(res => {
        if(res.code == 200){
          this.$message({
             type: 'success',
             message: res.msg
          });
        }else{
          this.$message({
             type: 'error',
             message: res.msg
          });
        }
      })
    },
    //立即支付
    handlePay(orderNo, item) {
      var orderNos = orderNo;
      if(item.comboOrderNo && item.comboOrderNo.substring(0, 2) == 'UC'){
        orderNos = item.comboOrderNo
      }
      location.href = this.URL.mall+'/meal/cashierOrder?productOrderNo='+orderNos+'&orderType='+item.orderType+''
      // this.$router.push({
      //   name: 'MealCashierOrder',
      //   query: {
      //     productOrderNo: orderNos,
      //     orderType: item.orderType
      //   }
      // })
    },
    //取消订单
    handleCancelOrder(orderId) {
      this.$confirm('是否确认取消订单？', '取消订单提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.cancelOrder(orderId)
      }).catch(() => {

      });
    },
    cancelOrder(orderId) {
      const params = {
        orderId: orderId,
        userId: this.getUserInfo().id
      }
      cancelOrder(params).then(res => {
        if(res.code == 200){
          this.$message({
            type: 'success',
            message: res.msg
          });
          this.getOrderList();
        }else{
          this.$message({
            type: 'error',
            message: res.msg
          });
        }
      })
    },
    //再次购买
    handleAgainBuy(orderNo) {
      this.againBuyOrder(orderNo);
    },
    againBuyOrder(orderNo) {
      const params = {
        orderNo: orderNo
      }
      let ids = ''
      againBuyOrder(params).then(res => {
        if(res.code == 200){
          res.data.forEach((item, i) => {
            ids+=item + ','
          })
          location.href = this.URL.mall+'/cart/list?againIds='+ids.substring(0, ids.length-1)
          // this.$router.push({
          //   name: 'CartList',
          //   query: {
          //     againIds: ids.substring(0, ids.length-1)
          //   }
          // })
        }
      })
    },
    //申请售后
    handleCancelSalesOrder(orderId) {
      const h = this.$createElement;
      this.$msgbox({
        title: '申请售后',
        customClass: 'sales-msgbox',
        message: h('p', null, [
          h('span', null, '售后申请项： '),
          h('i', null, '取消订单并退款'),
          h('p', { style: 'color: #999' }, '请与卖家事先协商再提交申请，若卖家同意，则款项原路退回。')
        ]),
        showCancelButton: true,
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      }).then(() => {
        console.log(orderId)
        this.applyCancelOrder(orderId)
      }).catch(() => {

      });
    },
    applyCancelOrder(orderId) {
      const params = {
        orderId: orderId,
        userId: this.getUserInfo().id
      }

      applyCancelOrder(params).then(res => {
        if(res.code == 200){
          this.$message({
            type: 'success',
            message: res.msg
          });
        }else{
          this.$message({
            type: 'error',
            message: res.msg
          });
        }
      })
    },
    //确认收货
    handleConfirmReceipt(orderNo) {
      const h = this.$createElement;
      this.$msgbox({
        title: '确认收货提示',
        customClass: 'sales-msgbox',
        message: h('p', null, [
          h('span', null, '是否确认已经收到货物？'),
          h('p', { style: 'color: #999' }, '确认收货后，货款将结算给卖家，请务必收到货后，再点击确认！')
        ]),
        showCancelButton: true,
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      }).then(() => {
        console.log(orderNo)
        this.confirmReceipt(orderNo)
      }).catch(() => {

      });
    },
    confirmReceipt(orderNo) {
      console.log(orderNo)
      const params = {
        orderNo: orderNo
      }

      confirmReceipt(params).then(res => {
        if(res.code == 200){
          this.$message({
            type: 'success',
            message: res.msg
          });
          this.getOrderList();
        }else{
          this.$message({
            type: 'error',
            message: res.msg
          });
        }
      })
    },
    //合并支付单选
    handleChangeItem(item) {
      if(item.checked){
        this.$set(item, 'checked', true)
        this.checkedLen ++;
      }else{
        this.$set(item, 'checked', false)
        this.checkedLen --;
      }
      if(this.checkedLen == this.orderList.length){
        this.checkedAll = true
      }else{
        this.checkedAll = false
      }
    },
    //合并支付全选
    handleChangeAll() {
      if(this.checkedAll){
        this.checkedAll = true
      }else{
        this.checkedAll = false
      }
      this.orderList.forEach((item, i) => {
        if(this.checkedAll){
          this.$set(item, 'checked', true)
          this.checkedLen = this.orderList.length;
        }else{
          this.$set(item, 'checked', false)
          this.checkedLen = 0;
        }
      })
    },
    //合并支付
    handleMergePlay() {
      let orderNos = ''
      this.orderList.forEach((item, i) => {
        if(item.checked){
          orderNos += item.orderNo + ','
        }
      })
      orderNos = orderNos.substring(0, orderNos.length-1)
      if(orderNos == ''){
        this.$message({
          type: 'error',
          message: '请选择需要合并支付的订单'
        });
        return;
      }
      if(this.checkedLen == 1){ //单个支付
        location.href = this.URL.mall+'/meal/cashierOrder?productOrderNo='+orderNos
        // this.$router.push({
        //   name: 'MealCashierOrder',
        //   query: {
        //     productOrderNo: orderNos
        //   }
        // })
      }else{ //合并支付
        location.href = this.URL.mall+'/meal/cashierOrder?productOrderNo='+orderNos+'&payAll=true'
        // this.$router.push({
        //   name: 'MealCashierOrder',
        //   query: {
        //     productOrderNo: orderNos,
        //     payAll: true
        //   }
        // })
      }
    }
  }
}
</script>

<style lang="scss" scoped>
  @import '@/styles/pages/orderList.scss';
  .panel-order .order-product-list .xorder-list-icon{
    display: inline-block;
    width: 80px;
    height: 80px;
    text-align: center;
    margin-right: 10px;
    line-height: 80px;
    background-color: #DBE8F4;
    border-radius: 6px;
    img{
      vertical-align: middle;
      width: 48px;
      height: 48px;
      background: none;
      margin: 0 auto;
    }
  }
  .panel-order .order-product-list li .orderType{
    background-color: #5789B2;
    color: #fff;
    display: inline-block;
    padding: 2px 4px;
    width: 48px;
    border-radius: 4px;
    font-size: 12px;
  }
</style>
